package tgc.edu.exam.controller;

import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import tgc.edu.exam.custom.AjaxResult;
import tgc.edu.exam.entity.Menu;
import tgc.edu.exam.entity.Permission;
import tgc.edu.exam.entity.TreeTableModel;
import tgc.edu.exam.form.MenuForm;
import tgc.edu.exam.service.MenuService;
import tgc.edu.exam.service.PermissionService;

@Controller
@RequestMapping("/menu")
public class MenuController {

	@Autowired
	private MenuService menuService;
	@Autowired
	private PermissionService permissionService;
	
	@RequestMapping("/manage")
	public String page() {
		return "menu/manage";
	}

	@RequestMapping(value="/treeList")
	@ResponseBody
	public Object treeList() {
		Sort sort=Sort.by("idx1");
		List<Menu> list = menuService.findAll(sort);
		return new TreeTableModel(list);
	}
	@RequestMapping("/edit")
	public String edit(MenuForm form, ModelMap map) {
		Menu model = new Menu();
		Integer id = form.getId();
		Integer parentId = form.getParentId();	//父级id
		if(id != null) {
			model = menuService.findById(id);
			parentId = model.getParentId();
		}
		if(parentId != null) {	//父级id
			Menu parent = menuService.findById(parentId);
			model.setParent(parent);
		}
		map.put("model", model);
		List<Permission> permissions = permissionService.findAll(Sort.by("idx1"));
		map.put("roles", permissions);
		return "menu/edit";
	}
	@RequestMapping(value="/save")
	@ResponseBody
	public Object save(MenuForm form) {
		try {
			Menu model = new Menu();
			Integer id = form.getId();
			if(id != null) {
				model = menuService.findById(id);
			}
			//父级菜单id
			Integer parentId = form.getParentId();
			if(parentId == null) {
				model.setParent(null);
			}else {
				model.setParent(new Menu(parentId));
			}
			//权限id
			Integer roleId = form.getRole().getId();
			if(roleId == null) {
				model.setRole(null);
			}else {
				Permission role = permissionService.findById(roleId);
				model.setRole(role);
			}
			BeanUtils.copyProperties(form, model,"id","role","parent");
			menuService.save(model);
			return new AjaxResult("数据保存成功！");
		} catch (Exception e) {
			return new AjaxResult(false,"数据保存失败");
		}
	}

	@RequestMapping("/delete")
	@ResponseBody
	public Object delete(MenuForm form) {
		try {
			menuService.deleteById(form.getId());
			return new AjaxResult("数据删除成功");
		} catch (Exception e) {
			return new AjaxResult(false, "数据删除失败");
		}
	}

}
